import os
import time
import cv2


def compare(image1, image2):
    zhifangtu1 = cv2.calcHist([image1], [0], None, [256], [0, 256])
    zhifangtu2 = cv2.calcHist([image2], [0], None, [256], [0, 256])
    return cv2.compareHist(zhifangtu1, zhifangtu2, 0)


date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
moment = time.strftime("%H.%M.%S", time.localtime(time.time()))

folder = 'work/' + date
if not os.path.exists(folder):
    os.makedirs(folder, 0o777)

newFile = moment + ".jpg"
imagePath = folder + '/' + newFile

cmd = "gst-launch-1.0 nvarguscamerasrc num-buffers=1 ! 'video/x-raw(memory:NVMM), width=1920, height=1080, format=NV12' ! nvjpegenc !filesink location=%s" % (
    imagePath)
os.system(cmd)
locals()

files = os.listdir(folder)
if len(files) >= 2:
    files.sort()
    nowImage = cv2.imread(folder + '/' + files[-1])
    oldImage = cv2.imread(folder + '/' + files[-2])
    similarity = compare(nowImage, oldImage)
    if similarity > 0.9:
        os.remove(folder + '/' + files[-1])
    else:
        os.system("git pull && git add . && git commit -m collected && git push ")

